<template>
  <div>
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.enterprise_name" placeholder="企业名称查询" clearable>
          <i class="el-icon-search el-input__icon" slot="suffix" @click="getData()"></i>
        </el-input>
      </el-form-item>

      <el-form-item>
        <c-select
          :options="enumProctStatus"
          placeholder="项目状态"
          clearable
          @change="getSelectData"
          v-model="proctStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumPayStatus"
          placeholder="付款状态"
          v-model="params['pay_status.eq']"
          @change="getData()"
          clearable
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumSignStatus"
          placeholder="签约状态"
          v-model="params['customer_sign_status.eq']"
          @change="getData()"
          clearable
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumInvoiceStatus"
          placeholder="发票状态"
          v-model="params['invoice_status.eq']"
          clearable
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button @click="handleFlow">
          <i class="fa fa-sitemap"></i>
          审批流程
        </el-button>
      </el-form-item>
      <div class="text-muted">
        <div>合计：</div>
        项目总数：
        <span class="text-primary">{{ totalCount || '-' }}</span>
      </div>
    </el-form>
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:status="scope">
        <span class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.status }}
        </span>
      </template>
      <template v-slot:inStatus="scope">
        <span class="badge" :class="`badge-${scope.row.invoiceStyle}`">
          {{ scope.row.invoiceStatus }}
        </span>
      </template>

      <template v-slot:signStatus="scope">
        <span
          class="badge"
          :class="`badge-${+scope.row.customer_sign_status === 1 ? 'success' : 'info'}`"
        >
          {{ scope.row.signStatus }}
        </span>
        <div>
          <small>{{ scope.row.customer_sign_time || '' }}</small>
        </div>
      </template>
      <template v-slot:payStatus="scope">
        <span class="badge" :class="`badge-${+scope.row.pay_status === 2 ? 'success' : 'info'}`">
          {{ enumPayStatus[scope.row.pay_status] }}
        </span>
        <div>
          <small>{{ scope.row.pay_time || '' }}</small>
        </div>
      </template>

      <template v-slot:oper="scope">
        <el-button
          type="text"
          @click="handleApprove(scope.row)"
          title="审批"
          class="mx-2 px-0"
          v-if="scope.row.editEnable"
        >
          <i class="fa fa-legal"></i>
        </el-button>
        <el-popover placement="top-start" title="客户签约地址" trigger="hover">
          <el-button @click="handleCopy(customerUrl)" type="text" class="ml-0 pl-0">
            复制链接
          </el-button>

          <div>扫描二维码</div>
          <div>
            <qr-code :value="customerUrl" :size="140"></qr-code>
          </div>
          <el-button slot="reference" type="text">
            <i class="fa fa-link"></i>
          </el-button>
        </el-popover>
        <el-button type="text" @click="handleView(scope.row)" title="查看" class="mx-1 px-0">
          <i class="fa fa-search"></i>
        </el-button>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <el-dialog append-to-body :visible.sync="infoVisible" width="80%">
      <el-tabs>
        <el-tab-pane label="项目信息">
          <info-view :query-id="infoId"></info-view>
        </el-tab-pane>
        <el-tab-pane label="审批信息">
          <approve-view :query-id="infoId" :view-mode="true"></approve-view>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <approve-dialog
      :visible.sync="approveVisible"
      :query-id="approveId"
      @success="getData()"
    ></approve-dialog>

    <flow-dialog title="审批流程" :visible.sync="flowVisible" :flow-key="flowKey"></flow-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import InfoView from '@/bigcredit/views/letter/apply/info/Index'
import { enumInvoiceStatus, enumInvoiceStyle } from '@/bigcredit/views/letter/apply/Index'
import { copyText } from '@vimi/utils-tool'
import ApproveDialog from '@/bigcredit/views/letter/approve/components/MainDialog'
import ApproveView from '@/bigcredit/views/letter/approve/components/Main'
import { wfKey } from '@/bigcredit/views/letter/approve/components/index'
import FlowDialog from '@/credit/components/flow/ViewDialog'
import { getFollow } from '@/credit/mixin/taskTableCountyUnionProvince'
export const enumSignStatus = {
  0: '未签约',
  1: '已签约',
}

export const enumPayStatus = {
  0: '未支付',
  1: '支付中',
  2: '已支付',
}

export default {
  components: {
    InfoView,
    ApproveDialog,
    FlowDialog,
    ApproveView,
  },
  props: {},
  data() {
    return {
      enumSignStatus,
      enumPayStatus,
      enumProctStatus: [
        {
          label: '待审批',
          value: JSON.stringify({
            'approval_status.lt': 2,
          }),
        },
        {
          label: '审批通过',
          value: JSON.stringify({
            'approval_status.eq': 2,
          }),
        },
        {
          label: '异常终止',
          value: JSON.stringify({
            'is_terminate.eq': 1,
          }),
        },
        {
          label: '审批拒绝',
          value: JSON.stringify({
            'approval_status.eq': 3,
          }),
        },
      ],
      flowKey: wfKey,
      enumInvoiceStatus,
      params: {
        index: 1,
        size: 15,
        'claim_status.eq': 1,
      },
      loading: false,
      totalCount: 0,
      tableName: 'guarantee_project_view',
      tableData: [],
      tableColumns: [
        { attrs: { label: '序号', prop: 'index', align: 'center' } },
        { attrs: { label: '企业名称', prop: 'enterprise_name', align: 'center' } },
        { attrs: { label: '保函类型', align: 'center' }, process: () => '投标保函' },
        { attrs: { label: '申请时间', prop: 'create_time', width: 100 } },
        { attrs: { label: '担保金额（元）', prop: 'tender_bond', align: 'center' } },
        {
          attrs: { label: '担保费率', prop: 'gua_rate', align: 'center' },
          process: v => (v ? v + ' ‰' : ''),
        },
        { attrs: { label: '担保费（元）', prop: 'gua_fee', align: 'center' } },
        { attrs: { label: '业务流程', prop: 'process', align: 'center' } },
        { attrs: { label: '项目状态', prop: 'status', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '客户付款', prop: 'payStatus', align: 'center', width: 90 },
          slot: 'payStatus',
        },
        // {
        //   attrs: { label: '客户签约', prop: 'signStatus', align: 'center', width: 90 },
        //   slot: 'signStatus',
        // },
        { attrs: { label: '待处理人', prop: 'itemStatusLabel', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', width: 120, fixed: 'right' },
          slot: 'oper',
        },
        // {
        //   attrs: { label: '操作', align: 'center', width: 100, fixed: 'right' },
        //   operations: [
        //     {
        //       content: '签约地址',
        //       icon: 'fa fa-link',
        //     },
        //     {
        //       content: '查看',
        //       icon: 'fa fa-search',
        //       event: this.handleView,
        //       attrs: { class: 'p-0 m-2' },
        //     },
        //   ],
        // },
      ],

      infoVisible: false,
      infoId: '',

      approveVisible: false,
      approveId: '',
      flowVisible: false,
      proctStatus: '',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'userId']),
    customerUrl() {
      return window.location.origin + '/letter/#/'
    },
  },
  watch: {},
  created() {
    this.params['service_id.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    getSelectData() {
      this.params['is_terminate.eq'] = ''
      this.params['approval_status.eq'] = ''
      this.params['approval_status.lt'] = ''
      if (this.proctStatus) {
        this.params = { ...this.params, ...JSON.parse(this.proctStatus) }
      }
      this.getData()
    },
    handleFlow() {
      this.flowVisible = true
    },
    handleCopy(value) {
      const success = copyText(value)
      if (success) {
        this.$message.success('已复制到粘贴板')
      } else {
        this.$message.error('已复制到粘贴失败')
      }
    },
    handleView(row = {}) {
      this.infoId = row.customer_related_id
      this.infoVisible = true
    },
    handleApprove(row = {}) {
      this.approveVisible = true
      this.approveId = row.customer_related_id ?? ''
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, { create_time: 'desc' })
        .then(res => {
          const data = res?.data ?? {}
          this.totalCount = data.totalCount ?? 0
          this.tableData = (data.data ?? []).map(this.dataAdapter)
          return getFollow(this.tableData, this.flowKey)
        })
        .then(follow => {
          this.tableData = this.tableData.map(it => {
            const data = follow.find(item => item.wf_related_id === it.customer_related_id) || {}
            it.itemStatusLabel = +it.confuse_status === 3 ? `已拒绝` : data.innerFollow || ''
            it.editEnable = data.task_person?.includes(this.userId) ?? false
            return it
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(row, index) {
      row.index = this.totalCount - index - this.params.size * (this.params.index - 1)
      if (+row.claim_status === 2) {
        row.process = '受理拒绝'
      } else if (+row.approval_status === 3) {
        row.process = '审批拒绝'
      } else if (+row.claim_status === 0) {
        row.process = '1.待业务部受理'
      } else if (+(row.approval_status || '') < 2) {
        row.process = `2.待审批`
      } else if (+row.pay_status < 2) {
        row.process = '3.订单待完成'
      } else if (+row.pay_status === 2) {
        row.process = '4.订单已完成'
      }
      row.statusStyle = 'warning'
      if (+row.is_terminate === 1) {
        row.status = '异常终止'
        row.statusStyle = 'danger'
      } else if (+row.claim_status === 2 || +row.approval_status === 3) {
        row.process = '已拒绝'
        row.status = '已拒绝'
        row.statusStyle = 'danger'
      } else if (+row.claim_status === 0) {
        row.status = '待受理'
      } else if (+row.pay_status < 2) {
        row.status = '订单待完成'
      } else if (+row.pay_status === 2) {
        row.status = '订单完成'
        row.statusStyle = 'success'
      } else {
        row.status = '待审批'
      }
      row.invoiceStatus = enumInvoiceStatus[row.invoice_status]
      row.invoiceStyle = enumInvoiceStyle[row.invoice_status]
      row.payInfo = row.pay_time ? row.pay_time : '暂无支付信息'
      row.signStatus = enumSignStatus[row.customer_sign_status]
      row.itemStatusLabel = ''

      return row
    },
  },
}
</script>

<style lang="scss" scoped></style>
